﻿using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shell;
using System.Xml.Linq;
using CommunityToolkit.Mvvm.Messaging;
using DynamicData;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SimpleTool.ActivityUnit;
using SimpleTool.ActivityUnit.EchoControl;
using SimpleTool.Base;
using SimpleTool.SerialTool;
using SimpleTool.SerialTool.SerialControl;
using SimpleTool.Server;
using SimpleTool.TransformComponent;

namespace SimpleTool
{
    class MainViewModel : Notify
    {
        public MainSectionModel.FuncType CurrentPageType = MainSectionModel.FuncType.Invalid;

        private MainSectionModel? MainTemplateModel;

        private readonly IDataBaseServer DBServer;

        private readonly IDirFileServer IOServer;

        private readonly IActivityDetetorServer ADServer;

        private readonly ILogger Logger = Log.ForContext<MainViewModel>();

        public UIBind VarbinUIBindStdin = new(Interfacial.Invalid) { IsPlayAnimation = true };

        public CornerRadius VarbinWindowRadiusStdin = new (12);

        public Action<bool>? RuntimeLogLift = null;

        public Action? WinDragMoveLift = null;

        public Action<int>? WinActionLift = null;

        public VerticalAlignment VarbinFuncListverAlignStdin = VerticalAlignment.Center;

        private Dictionary<string, WeakReference<FrameworkElement>> IndependentMap = [];

        public ObservableCollection<MainFuncListItem> MainFuncListItems { set; get; } = [];

        public ObservableCollection<TopMenuOptions> HoldTitleTopMenuOptions { set; get; } = [];

        public ICommand? CmdFuncSelectedStdin;

        public ICommand? CmdDragMoveStdin;

        public ICommand? CmdTitleNorStdin;

        public ICommand? CmdTitleFlexStdin;

        public ICommand? CmdTitleCloseStdin;

        public ICommand? CmdTitleOrderViewStdin;

        public ICommand? CmdTitleRegexpToolStdin;

        public ICommand? CmdTitleBitwiseStdin;

        public ICommand? CmdTitleTestResultStdin;

        public ICommand CmdFuncSelected
        {
            set
            {
                CmdFuncSelectedStdin = value;
                propertyChangeSend(nameof(CmdFuncSelected));
            }
            get
            {
                CmdFuncSelectedStdin ??= new EasyCommand(MMenu_SelectEvent, bool () => { return true; });
                return CmdFuncSelectedStdin;
            }
        }

        public ICommand CmdDragMove
        {
            set
            {
                CmdDragMoveStdin = value;
                propertyChangeSend(nameof(CmdDragMove));
            }
            get
            {
                CmdDragMoveStdin ??= new EasyCommand((obj) => { WinDragMoveLift?.Invoke(); }, bool () => { return true; });
                return CmdDragMoveStdin;
            }
        }

        public ICommand CmdTitleNor
        {
            set
            {
                CmdTitleNorStdin = value;
                propertyChangeSend(nameof(CmdTitleNor));
            }
            get
            {
                CmdTitleNorStdin ??= new EasyCommand(Win_NorEvent, bool () => { return true; });
                return CmdTitleNorStdin;
            }
        }

        public ICommand CmdTitleFlex
        {
            set
            {
                CmdTitleFlexStdin = value;
                propertyChangeSend(nameof(CmdTitleFlex));
            }
            get
            {
                CmdTitleFlexStdin ??= new EasyCommand(Win_FlexEvent, bool () => { return true; });
                return CmdTitleFlexStdin;
            }
        }

        public ICommand CmdTitleClose
        {
            set
            {
                CmdTitleCloseStdin = value;
                propertyChangeSend(nameof(CmdTitleClose));
            }
            get
            {
                CmdTitleCloseStdin ??= new EasyCommand(Win_CloseEvent, bool () => { return true; });
                return CmdTitleCloseStdin;
            }
        }

        public ICommand CmdTitleOrderView
        {
            set
            {
                CmdTitleOrderViewStdin = value;
            }
            get
            {
                CmdTitleOrderViewStdin ??= new EasyCommand((obj) => TitleTopMenu(obj, nameof(EnjoyTable)), bool () => { return true; });
                return CmdTitleOrderViewStdin;
            }
        }

        public ICommand CmdTitleRegexpTool
        {
            set
            {
                CmdTitleRegexpToolStdin = value;
            }
            get
            {
                CmdTitleRegexpToolStdin ??= new EasyCommand((obj) => {
                    Logger.Print(RuntimeLog.LogType.Debug, "点击ile");
                    TitleTopMenu(obj, nameof(RegexpTestTool));
                }, bool () => { return true; });
                return CmdTitleRegexpToolStdin;
            }
        }

        public ICommand CmdTitleBitwise
        {
            set
            {
                CmdTitleBitwiseStdin = value;
            }
            get
            {
                CmdTitleBitwiseStdin ??= new EasyCommand((obj) => TitleTopMenu(obj, nameof(BitwiseXorUI)), bool () => { return true; });
                return CmdTitleBitwiseStdin;
            }
        }

        public ICommand CmdTitleTestResult
        {
            set
            {
                CmdTitleTestResultStdin = value;
            }
            get
            {
                CmdTitleTestResultStdin ??= new EasyCommand((obj) => TitleTopMenu(obj, nameof(TestStatisticialTree)), bool () => { return true; });
                return CmdTitleTestResultStdin;
            }
        }

        public VerticalAlignment VarbinFuncListverAlign
        {
            set
            {
                VarbinFuncListverAlignStdin = value;
                propertyChangeSend(nameof(VarbinFuncListverAlign));
            }
            get
            {
                return VarbinFuncListverAlignStdin;
            }
        }

        public MainSectionModel HoldSectionModel
        {
            set
            {
                MainTemplateModel = value;
                propertyChangeSend(nameof(HoldSectionModel));
            }
            get
            {
                MainTemplateModel ??= new MainSectionModel();
                return MainTemplateModel;
            }
        }

        public UIBind VarbinUIBind
        {
            set
            {
                VarbinUIBindStdin = value;
                propertyChangeSend(nameof(VarbinUIBind));
            }
            get
            {
                return VarbinUIBindStdin;
            }
        }

        public CornerRadius VarbinWindowRadius
        {
            set
            {
                VarbinWindowRadiusStdin = value;
                propertyChangeSend(nameof(VarbinWindowRadius));
            }
            get
            {
                return VarbinWindowRadiusStdin;
            }
        }

        private readonly Dictionary<string, (string menuName, string icon, ICommand command)> MenuMap = [];

        public MainViewModel(IDataBaseServer DataBaseServer,
                             IDirFileServer DirFileServer,
                             IActivityDetetorServer ActivityDetetorServer)
        {
            DBServer = DataBaseServer;

            IOServer = DirFileServer;

            ADServer = ActivityDetetorServer;

            ADServer.SetDelegate(UIIndependent);

            VarbinUIBind.InstantiationCallBack = () =>
            {
                VarbinUIBind.IsPlayAnimation = false;
            };

            MenuMap.Add(nameof(TestStatisticialTree), ("测试结果", "\ue626", CmdTitleTestResult));
            MenuMap.Add(nameof(BitwiseXorUI), ("位异或工具", "\ue60a", CmdTitleBitwise));
            MenuMap.Add(nameof(RegexpTestTool), ("正则工具", "\ue6fc", CmdTitleRegexpTool));
            MenuMap.Add(nameof(EnjoyTable), ("工单预览", "\ue6a3", CmdTitleOrderView));

            Logger.Print(RuntimeLog.LogType.Debug, $"[Software FrameWork]: {RuntimeInformation.FrameworkDescription}");
        }

        public void UIIndependent(Dictionary<string, WeakReference<FrameworkElement>> Map)
        {
            IndependentMap = Map;

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                ObservableCollection<TopMenuOptions> TemplateItems = [];

                foreach (var kvp in Map)
                {
                    IEnumerable<string> HoldNames = TemplateItems.Select(x => x.MenuName);

                    if (MenuMap.TryGetValue(kvp.Key, out (string menuName, string icon, ICommand command) value))
                    {
                        Logger.Print(RuntimeLog.LogType.Fatal, HoldNames.Join(" -  "), value.menuName);
                        if (!HoldNames.Contains(value.menuName))
                        {
                            TemplateItems.Add
                            (
                                new TopMenuOptions
                                {
                                    Icon = value.icon,
                                    MenuName = value.menuName,
                                    Command = value.command
                                }
                            );
                        }
                    }
                             
                    if (kvp.Value.TryGetTarget(out FrameworkElement? Element))
                    {
                        Element.Unloaded += TopMenuOptionsUnloader;
                    }
                }

                HoldTitleTopMenuOptions = TemplateItems;

                propertyChangeSend(nameof(HoldTitleTopMenuOptions));
            });
        }

        public void TopMenuOptionsUnloader(object sender, RoutedEventArgs e)
        {
            if (sender is FrameworkElement Element &&
                MenuMap.TryGetValue(Element.Name, out (string, string, ICommand) value))
            {
                int indexof = HoldTitleTopMenuOptions.Select(x => x.MenuName).IndexOf(value.Item1);

                if (indexof != -1)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        HoldTitleTopMenuOptions.RemoveAt(indexof);
                        ADServer.Independent(Element.Name);
                        propertyChangeSend(nameof(HoldTitleTopMenuOptions));
                    });
                }
                Element.Unloaded -= TopMenuOptionsUnloader;
            }
        }

        public void TitleTopMenu(object? param, string name)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (IndependentMap.TryGetValue(name, out WeakReference<FrameworkElement>? WeakElement))
                {
                    if (WeakElement.TryGetTarget(out FrameworkElement? Element))
                    {
                        if (Element is Window window)
                        {
                            window.WindowState = WindowState.Normal;
                            window.Topmost = true;
                            window.Activate();
                            window.Topmost = false;
                        }
                    }
                }
            });
        }

        public async Task Init()
        {
            var readLocal = await IOServer.ReadIniAsync(LocalConfig.Path.Object.G_Path(LocalConfig.Path.FileType.Nor));

            //  read db type
            if (readLocal.TryGetValue(LocalConfig.OwnerKey.DB, out Dictionary<string, string>? _DB) &&
                _DB.TryGetValue($"{LocalConfig.DBCacheTreeKey.IsCloud}", out string? _IsCloud) &&
                bool.TryParse(_IsCloud, out bool IsCloud))
            {
                if (IsCloud)
                {
                    Logger.Print(RuntimeLog.LogType.Info, "open cloud db now");
                }
                else
                {
                    Logger.Print(RuntimeLog.LogType.Info, "open local db now");
                }
                OpenSetting.option.SetDBType(IsCloud); // *** 缺少后会导致数据库历史选项恢复，从而程序在打开后自动变为云数据库
                DBinit(IsCloud);
            }
            else
            {
                Logger.Print(RuntimeLog.LogType.Info, "empty db config, connect cloud db now");
                DBinit(OpenSetting.option.IsColudDB());
            }

            //  read rtlog ui state
            if (readLocal.TryGetValue(LocalConfig.OwnerKey.Log, out Dictionary<string, string>? _LOG) &&
                _LOG.TryGetValue($"{LocalConfig.RuntimeLogKey.OpeningLogTextBox}", out string? _OpeningLogTextBox) &&
                bool.TryParse(_OpeningLogTextBox, out bool OpeningLogTextBox))
            {
                OpenSetting.option.CutLog(OpeningLogTextBox ? "开" : "关");
                RuntimeLogLift?.Invoke(OpeningLogTextBox);
            }
            else
            {
                Logger.Print(RuntimeLog.LogType.Info, "empty log config, log box is setting visible now");
                RuntimeLogLift?.Invoke(OpenSetting.option.IsOpenLog() == "开");
            }

            //  read mmstyle ui state
            if (readLocal.TryGetValue(LocalConfig.OwnerKey.BS, out Dictionary<string, string>? _MMenu) &&
                _MMenu.TryGetValue($"{LocalConfig.BSCacheTreeKey.FuncIconStyle}", out string? _FuncIconStyle) &&
                HoldSectionModel.PublicSettingTranslateMap.TryGetValue(_FuncIconStyle.ToLower(), out string? translation))
            {
                OpenSetting.option.CutMenu(translation);
            }
            else
            {
                Logger.Print(RuntimeLog.LogType.Info, "empty log config, log box is setting visible now");
            }
            MMenu_SelectEvent(1);
            GenerateLocalKey();
        }

        public async void GenerateLocalKey()
        {
            foreach (PropertyInfo field in typeof(OpenSetting).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (OpenSetting.option.FieldKeyRelationMap.TryGetValue(field.Name, out (string, string, LocalConfig.Path.FileType) infogroup))
                {
                    if (field.GetValue(OpenSetting.option) is not null and object _value)
                    {
                        if (HoldSectionModel.PublicSettingTranslateMap.GetSafetyKey(_value.GetSafetyChar()) is not null and ICollection<string> _RealValues &&
                            _RealValues.Count == 1)
                        {
                            await IOServer.WriteIniAsync(LocalConfig.Path.Object.G_Path(infogroup.Item3), infogroup.Item2,
                                                         infogroup.Item1,
                                                         _RealValues.ElementAt(0));
                        }
                        else
                        {
                            await IOServer.WriteIniAsync(LocalConfig.Path.Object.G_Path(infogroup.Item3), infogroup.Item2,
                                                         infogroup.Item1,
                                                         _value);
                        }
                    }
                }
            }
        }

        public void DBinit(bool isCloud = true, bool isAbnormal = false)
        {
            if (DBServer is not null)
            {
                if (isCloud)
                {
                    DBServer.InitCloudDB(DBServer.GetImportantInfo().Key,
                                         DBServer.GetImportantInfo().Value, async (state) =>
                    {
                        if (!state)
                        {
                            await CustomMessageBox.Show(
                                new CustomMessageBox.InquiryNmPopupSetting { 
                                    Msg_Title = "云数据库连接异常", 
                                    Msg_InquiryIcon = 1,
                                    Msg_BodyText = "因为云数据库连接失败，暂时无法使用，正在尝试切换至本地数据库", 
                                    Msg_InquiryButtoms = ["知道了"] });
                            DBinit(false, true);
                            Logger.Print(RuntimeLog.LogType.Warning, "cloud init fail");
                        }
                        else
                        {
                            OpenSetting.option.CutDB("云数据库", "云数据库");
                            DBServer.TemporaryRelease(true);//  释放原数据库资源，先释放，给CheckDBSurvival一个正确的判断，确保后续的查询有效
                            if (isAbnormal) await ReffleUpdate(); //  异常情况下，切换数据库之后将重新加载数据
                            Logger.Print(RuntimeLog.LogType.Warning, "cloud init finish");
                        }
                    });
                }
                else
                {
                    DBServer?.InitLocalDB(new SqliteConnectionConfig
                    {
                        Path = DBServer.GetImportantInfo(false).Key,
                        Name = DB.G_MapKeyName(DB.DB_MAPKEY.LocalDataCache),
                        Password = string.Empty,
                        Way = DatabaseConnectWay.ReadWriteCreate
                    }, 
                    async (state) =>
                    {
                        if (DBServer is not null)
                        {
                            if (state)
                            {
                                OpenSetting.option.CutDB("本地数据库", "Auto");
                                DBServer.TemporaryRelease(false);//  释放原数据库资源，先释放，给CheckDBSurvival一个正确的判断，确保后续的查询有效
                                if (isAbnormal) await ReffleUpdate(); //  异常情况下，切换数据库之后将重新加载数据
                            }
                            else
                            {
                                Logger.Print(RuntimeLog.LogType.Error, "local sqlite database init faillilg, cheke true of db path or key");
                            }
                        }
                    });
                }
            }
        }

        public void PublicSettingQuestion()
        {
            List<(string, string, string, object)> Changes = [];

            CustomMessageBox.PublicBlackBox InquiryOption = CustomMessageBox.Show(
                new CustomMessageBox.InquiryPBLPopupSetting
                {
                    Msg_Title = "公共配置",
                    Msg_InquiryButtoms = ["取消", "确定"],
                    Msg_PBLSetting = new CustomMessageBox.PublicBlackBox
                    {
                        CurrentApplyDBaddress = OpenSetting.option.DBPair().Item1,
                        CurrentApplyDBkey = OpenSetting.option.DBPair().Item2,
                        CurrentApplyLogState = OpenSetting.option.IsOpenLog(),
                        CurrentApplyMMenuStyle = OpenSetting.option.MenuStyle()
                    },
                    Msg_WinRadius = 8
                });

            if (InquiryOption.index == 1)
            {
                if (InquiryOption.CurrentApplyDBaddress == "云数据库")
                {
                    if (InquiryOption.CurrentApplyDBkey != "云数据库")
                    {
                        DBServer.SetImportantInfo(new KeyValuePair<string, string>(
                        DBServer.GetImportantInfo().Key,
                        InquiryOption.CurrentApplyDBkey), true);
                        OpenSetting.option.CutDB(DBServer.GetImportantInfo().Key,InquiryOption.CurrentApplyDBkey);
                    }
                    else
                    {
                        OpenSetting.option.CutDB("云数据库", "云数据库");
                    }
                    OpenSetting.option.SetDBType(true);
                    DBinit(true, true);
                }
                else if (InquiryOption.CurrentApplyDBaddress == "本地数据库")
                {
                    if (InquiryOption.CurrentApplyDBkey == "云数据库")
                    {
                        DBServer.SetImportantInfo(new KeyValuePair<string, string>(
                        DBServer.GetImportantInfo(false).Key,
                        DBServer.GetImportantInfo().Value), false);
                        OpenSetting.option.CutDB(DBServer.GetImportantInfo(false).Key, DBServer.GetImportantInfo().Value);
                    }
                    else if (InquiryOption.CurrentApplyDBkey != "Auto")
                    {
                        DBServer.SetImportantInfo(new KeyValuePair<string, string>(
                        DBServer.GetImportantInfo(false).Key,
                        InquiryOption.CurrentApplyDBkey), false);
                        OpenSetting.option.CutDB(DBServer.GetImportantInfo(false).Key, InquiryOption.CurrentApplyDBkey);
                    }
                    OpenSetting.option.SetDBType(false);
                    DBinit(false, true);
                }
                else
                {
                    if (!string.IsNullOrEmpty(InquiryOption.CurrentApplyDBaddress) && !string.IsNullOrEmpty(InquiryOption.CurrentApplyDBkey))
                    {
                        OpenSetting.option.CutDB(InquiryOption.CurrentApplyDBaddress, InquiryOption.CurrentApplyDBkey);

                        DBinit(true, true);
                    }
                }

                if (OpenSetting.option.MenuStyle() != InquiryOption.CurrentApplyMMenuStyle)
                {
                    OpenSetting.option.CutMenu(InquiryOption.CurrentApplyMMenuStyle);
                    MMenu_ItemsUpdate(HoldSectionModel.StoryMMenuSelectItem, true);
                }

                OpenSetting.option.CutLog(InquiryOption.CurrentApplyLogState);
                if (HoldSectionModel.PublicSettingTranslateMap.GetSafetyKey(OpenSetting.option.IsOpenLog()) is not null and ICollection<string> _strstats &&
                    _strstats.Count == 0 &&
                    bool.TryParse(_strstats.ElementAt(0), out bool _realstat))
                {
                    RuntimeLogLift?.Invoke(_realstat);
                }

                GenerateLocalKey();
            }
        }

        //  数据库切换重连
        private async Task ReffleUpdate()
        {
            if (VarbinUIBind.UIType == Interfacial.PRDTActivity)
            {
                App MyApp = (App)Application.Current;
                ActivityViewModel ViewModel = MyApp.ServiceProvider.GetRequiredService<ActivityViewModel>();
                ViewModel.ReadyWork();
                Logger.Print(RuntimeLog.LogType.Debug, "ready work for activity");
            }
            else if (VarbinUIBind.UIType == Interfacial.SRLPSerialPort)
            {
                App MyApp = (App)Application.Current;
                SerialViewModel ViewModel = MyApp.ServiceProvider.GetRequiredService<SerialViewModel>();
                await ViewModel.ReadyWork();
                Logger.Print(RuntimeLog.LogType.Debug, "ready work for overview");
            }
        }

        private void MMenu_SelectEvent(object? selected)
        {
            int SelectType = (int)(selected ?? 0);
            switch (SelectType)
            {
                case 0:
                    switch (CurrentPageType)
                    {
                        case MainSectionModel.FuncType.Invalid:
                        case MainSectionModel.FuncType.Global:
                            PublicSettingQuestion();
                            break;
                        case MainSectionModel.FuncType.Serial:
                        case MainSectionModel.FuncType.Activity:
                        case MainSectionModel.FuncType.Capacity:
                            MMenu_ItemsUpdate(MainSectionModel.FuncType.Global);
                            break;
                    }
                    break;

                case 1:
                    switch (CurrentPageType)
                    {
                        case MainSectionModel.FuncType.Invalid:
                        case MainSectionModel.FuncType.Global:
                            VarbinUIBind.UIType = Interfacial.SRLPSerialPort;
                            VarbinUIBind.InstantiationCallBack = () =>
                            {
                                Task.Run(() =>
                                {
                                    App MyApp = (App)Application.Current;

                                    OverViewModel HoldViewModel = MyApp.ServiceProvider.GetRequiredService<OverViewModel>();

                                    HoldViewModel.PowerPlantServer.Read<OverViewModel>(HoldViewModel.SerialDataReceive);

                                    VarbinUIBind.IsPlayAnimation = false;
                                });
                            };
                            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.SerialPort_ChildPage, 2));
                            MMenu_ItemsUpdate(MainSectionModel.FuncType.Serial);
                            break;
                        case MainSectionModel.FuncType.Serial:
                            PublicSettingQuestion();
                            break;
                        case MainSectionModel.FuncType.Activity:
                            PublicSettingQuestion();
                            break;
                    }
                    break;

                case 2:
                    switch (CurrentPageType)
                    {
                        case MainSectionModel.FuncType.Global:
                            VarbinUIBind.UIType = Interfacial.CPCTCapacity;
                            MMenu_ItemsUpdate(MainSectionModel.FuncType.Capacity);
                            break;
                        case MainSectionModel.FuncType.Serial:
                            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.SerialPort_ChildPage, 2));
                            break;
                    }
                    break;

                case 3:
                    switch (CurrentPageType)
                    {
                        case MainSectionModel.FuncType.Global:
                            VarbinUIBind.UIType = Interfacial.PRDTActivity;
                            VarbinUIBind.InstantiationCallBack = () =>
                            {
                                Task.Run(() =>
                                {
                                    App MyApp = (App)Application.Current;

                                    ActivityViewModel HoldViewModel = MyApp.ServiceProvider.GetRequiredService<ActivityViewModel>();

                                    IPowerPlantServer PowerPlant = MyApp.ServiceProvider.GetRequiredService<IPowerPlantServer>();

                                    PowerPlant.Read<ActivityViewModel>(HoldViewModel.SerialDataReceive);
                                });
                            };
                            MMenu_ItemsUpdate(MainSectionModel.FuncType.Activity);
                            break;
                        case MainSectionModel.FuncType.Serial:
                            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.SerialPort_ChildPage, 3));
                            break;
                    }
                    break;

                case 4:
                    switch (CurrentPageType)
                    {
                        case MainSectionModel.FuncType.Global:
                            break;
                        case MainSectionModel.FuncType.Serial:
                            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.SerialPort_ChildPage, 4));
                            break;
                    }
                    break;
            }

            propertyChangeSend(nameof(VarbinUIBind));
        }

        private void Win_NorEvent(object? param)
        {
            WinActionLift?.Invoke(0);
        }

        private void Win_FlexEvent(object? param)
        {
            WinActionLift?.Invoke(1);
        }

        private void Win_CloseEvent(object? param)
        {
            WinActionLift?.Invoke(2);
        }

        public void MMenu_ItemsUpdate(MainSectionModel.FuncType Type, bool Peremptory = false)
        {
            HoldSectionModel.StoryMMenuSelectItem = Type;

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (Type != CurrentPageType || Peremptory)
                {
                    MainFuncListItems.Clear();
                    CurrentPageType = Type;

                    bool isChz = HoldSectionModel.PublicSettingTranslateMap.GetSafetyKey(OpenSetting.option.MenuStyle()) is not null and ICollection<string> _essenses 
                                 && _essenses.Count == 1 && _essenses.ElementAt(0) == nameof(MainSectionModel.MMenuSType.chz);

                    MainFuncListItems.AddRange(HoldSectionModel.GetFuncItems(Type, isChz));

                    VarbinFuncListverAlign = VerticalAlignment.Center;
                }
            });
        }
    }
}
